package me.shurufa.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.github.ybq.android.spinkit.SpinKitView;
import com.malinskiy.superrecyclerview.SuperRecyclerView;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.finalteam.okhttpfinal.HttpRequest;
import me.shurufa.R;
import me.shurufa.activities.NewDigestBookActivity;
import me.shurufa.adapter.SelectDigestBookAdapter;
import me.shurufa.bean.NoteBook;
import me.shurufa.model.AddDigestBean;
import me.shurufa.net.API;
import me.shurufa.net.RequestParams;
import me.shurufa.net.okhttp.callback.HttpCallback;
import me.shurufa.response.NoteBookListResp;
import me.shurufa.utils.Constants;
import me.shurufa.utils.LogUtils;
import me.shurufa.utils.NetworkUtils;
import me.shurufa.utils.RecyclerViewStateUtils;
import me.shurufa.utils.Utils;
import me.shurufa.widget.LoadingFooter;
import me.shurufa.widget.recyclerview.EndlessRecyclerOnScrollListener;
import me.shurufa.widget.recyclerview.HeaderAndFooterRecyclerViewAdapter;

/**
 * 作者 : andy
 * 日期 : 16/3/8 17:50
 * 邮箱 : andyxialm@gmail.com
 * 描述 : 我的书架Fragment
 */
public class SelectMyDigestBookFragment extends BaseFragment implements View.OnClickListener {

    @Bind(R.id.left_text)
    TextView leftText;

    @Bind(R.id.right_image)
    ImageView rightImage;

    @Bind(R.id.right_text)
    TextView rightText;

    @Bind(R.id.toolbar_title)
    TextView toolbar_title;

    @Bind(R.id.progress)
    SpinKitView progress;

    @Bind(R.id.recycler_view)
    SuperRecyclerView recyclerView;


    private AddDigestBean mAddDigestBean;
    private ArrayList<NoteBook> dataList;
    private SelectDigestBookAdapter mAdapter;
    private HeaderAndFooterRecyclerViewAdapter mHeaderAndFooterRecyclerViewAdapter = null;

    private int mPage = 1;
    private boolean hasMore = true;
    private View.OnClickListener mFooterClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (NetworkUtils.isNetAvailable(getActivity())) {
                RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView.getRecyclerView(), Constants.PAGE_REQUEST_COUNT, LoadingFooter.State.Loading, null);
                loadData(mPage);
            }
        }
    };


    /**
     * 创建
     * @return
     */
    public static SelectMyDigestBookFragment create(AddDigestBean addDigestBean) {
        SelectMyDigestBookFragment fragment = new SelectMyDigestBookFragment();
        Bundle args = new Bundle();
        args.putSerializable(Constants.ARG_ADD_DIGEST, addDigestBean);
        fragment.setArguments(args);
        return fragment;
    }

    private void parseArguments() {
        if (null != getArguments()) {
            mAddDigestBean = (AddDigestBean) getArguments().getSerializable(Constants.ARG_ADD_DIGEST);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_select_my_shelf_book, container, false);
        ButterKnife.bind(this, view);
        parseArguments();
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    protected void initUI(View view) {
        super.initUI(view);

        toolbar_title.setText(getString(R.string.select_digest_book));
        rightText.setVisibility(View.VISIBLE);
        rightText.setText(getString(R.string.new_build));
        rightText.setOnClickListener(this);

        dataList = new ArrayList<>();

        mAdapter = new SelectDigestBookAdapter(getActivity(), dataList, mAddDigestBean);
        mHeaderAndFooterRecyclerViewAdapter = new HeaderAndFooterRecyclerViewAdapter(mAdapter);
        recyclerView.setAdapter(mHeaderAndFooterRecyclerViewAdapter);

        //setLayoutManager
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(manager);
        recyclerView.getRecyclerView().addOnScrollListener(mOnScrollListener);

        // 默认隐藏，刷新后无数据的话才显示
        recyclerView.getEmptyView().setVisibility(View.GONE);
        if (recyclerView.getEmptyView() != null) {
            View v = recyclerView.getEmptyView();
            TextView empty_text = (TextView) v.findViewById(R.id.empty_text);
            empty_text.setText("书架上还没有图书，新建一本吧");
        }

        backInToolbar.setVisibility(View.GONE);
        rightText.setVisibility(View.VISIBLE);
        rightText.setText(getString(R.string.new_build));
        toolbar_title.setText(getString(R.string.select_digest_book));
        leftText.setOnClickListener(this);
        rightText.setOnClickListener(this);

        // 加载一次
        loadData(mPage);
    }


    /*@Override
    public void onEventMainThread(Intent intent) {
        super.onEventMainThread(intent);
        if (Constants.EVENT_ADD_NOTEBOOK_FROM_ADD_DIGEST.equals(intent.getAction())) {
            refresh();
        }
    }*/

    public void refresh() {
        mPage = 1;
        loadData(mPage);
    }


    private void loadData(final int page) {
        RequestParams params = new RequestParams();
        params.addFormDataPart("page", page);
        HttpRequest.post(API.GET_NOTEBOOK_BY_USER, params, new HttpCallback<NoteBookListResp>(getActivity()) {

            @Override
            public void onRespSuccess(NoteBookListResp noteBookListResp) {
                try {
                    handleResponse(noteBookListResp, (page == 0 || page == 1));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onRespFailure(NoteBookListResp noteBookListResp) {
                progress.setVisibility(View.GONE);
            }

            @Override
            public void onStart() {
                super.onStart();
                try {
                    if (NetworkUtils.isNetAvailable(getActivity())) {
                        RecyclerViewStateUtils.setFooterViewState(recyclerView.getRecyclerView(), LoadingFooter.State.Loading);
                    } else {
                        // 是上拉加载
                        if (mPage > 1) {
                            RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView.getRecyclerView(), Constants.PAGE_REQUEST_COUNT, LoadingFooter.State.NetWorkError, mFooterClick);
                        }

                        if (mPage == 1) {
                            progress.setVisibility(View.VISIBLE);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
                try {
                    refreshComplete();
                    if (mPage <= 2) {
                        progress.setVisibility(View.GONE);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Require run in UIThread
     */
    public void refreshComplete() {
        // 是上拉加载更多
        if (mPage > 1) {
            RecyclerViewStateUtils.setFooterViewState(recyclerView.getRecyclerView(), hasMore ? LoadingFooter.State.Normal : LoadingFooter.State.TheEnd);
        }

    }

    /**
     * 处理返回结果
     * 1. 去重
     * @param listResp     data
     * @param isPullToRefresh  boolean
     */
    private void handleResponse(NoteBookListResp listResp, boolean isPullToRefresh) {
        // 是否还有更多
        hasMore = !(listResp.data == null || Utils.isNullForList(listResp.data));

        // 1. 判空
        if (listResp.data == null || Utils.isNullForList(listResp.data)) {
            if (isPullToRefresh) {
                recyclerView.getEmptyView().setVisibility(View.VISIBLE);
            }
            return;
        }

        if (isPullToRefresh) {
            mAdapter.clear();
            mAdapter.notifyDataSetChanged();
        }

        mAdapter.append(listResp.data);
        mPage ++;

    }

    private EndlessRecyclerOnScrollListener mOnScrollListener = new EndlessRecyclerOnScrollListener() {

        @Override
        public void onLoadNextPage(View view) {
            super.onLoadNextPage(view);

            try {
                LoadingFooter.State state = RecyclerViewStateUtils.getFooterViewState(recyclerView.getRecyclerView());
                if(state == LoadingFooter.State.Loading) {
                    LogUtils.kLog().e("the state is Loading, just wait..");
                    return;
                }

                if (hasMore) {
                    if (!NetworkUtils.isNetAvailable(getActivity())) {
                        RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView.getRecyclerView(), Constants.PAGE_REQUEST_COUNT, LoadingFooter.State.NetWorkError, mFooterClick);
                        return;
                    }
                    // loading more
                    RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView.getRecyclerView(), Constants.PAGE_REQUEST_COUNT, LoadingFooter.State.Loading, null);
                    loadData(mPage);
                } else {
                    //the end
                    RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView.getRecyclerView(), Constants.PAGE_REQUEST_COUNT, LoadingFooter.State.TheEnd, null);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };


    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()){
            case R.id.right_text:
                intent = new Intent(getActivity(), NewDigestBookActivity.class);
                NewDigestBookActivity.initArgument(intent, Constants.TYPE_FROM_ADD_DIGEST_ADD_NOTEBOOK);
                startActivity(intent);
                break;
        }
    }

}
